package com.ibp.service.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.ibp.entity.HostMgr;
import com.ibp.entity.NodeMgr;
import com.ibp.service.DictDataService;
import com.ibp.service.NodeMgrService;
import com.ibp.service.FSHttpService;
import com.ibp.utils.PropertyUtils;
import com.ibp.utils.RegeUtils;
import com.ibp.utils.StringUtil;

@Service("nodeMgrServiceImpl")
public class NodeMgrServiceImpl implements NodeMgrService, InitializingBean {

	private static Logger logger = LoggerFactory
			.getLogger(NodeMgrServiceImpl.class);

	@Autowired
	PropertyUtils propertyUtils;

	@Autowired
	FSHttpService fSHttpServiceImpl;

	private String ibms_ip = null;
	private String ibms_port = null;
	private String url = null;
	private String ibms_nodes = null;
	private String query_nodes=null;
	private String add_node=null;
	private String delete_node=null;
	private String update_node=null;
	private String add_host=null;
	private String delete_host=null;
	  @Autowired
	  DictDataService dictDataServiceImpl;
	  private ServletContext servletContext; 

	@Override
	public List<NodeMgr> getNodeMgrList(NodeMgr filter) {
		List<NodeMgr> nodes = new ArrayList<NodeMgr>();

		
		String response = this.fSHttpServiceImpl.sendPostRequest(this.url
				+ this.query_nodes);
		if (!StringUtil.isEmpty(response)) {
			nodes = parseResponse(response);
		}
		logger.debug("查询NodeMgr结果：{}", nodes);
		// 过滤掉不符合条件的记录
		nodes = filter(nodes, filter);
		logger.debug("过滤后的结果：{}", nodes);
		return nodes;
	}

	/***
	 * 过滤结果集
	 * 
	 * @param list
	 * @param srm
	 * @return
	 */
	public List<NodeMgr> filter(List<NodeMgr> nodes, NodeMgr filter) {
		// 入参检查
		if (filter == null || (StringUtils.isBlank(filter.getNode()) && StringUtils.isBlank(filter.getHosts())  && StringUtils.isBlank(filter.getInvalid()))) {
			return nodes;
		}

		List<NodeMgr> result = new ArrayList<NodeMgr>();
		// 遍历每条记录的内容，若匹配则记入result
		for (NodeMgr entry : nodes) {
			if (RegeUtils.match(entry.getNode(), filter.getNode())
					&& RegeUtils.match(entry.getHosts(), filter.getHosts())
					&& RegeUtils.match(entry.getInvalid(), filter.getInvalid())){
				result.add(entry);
			}
		}
		return result;
	}

	protected List<NodeMgr> parseResponse(String response) {
		// 检查入参
		if (StringUtils.isBlank(response)) {
			return null;
		}
		String[] respStr = response.split("\n");
		for (String ss : respStr) {
			logger.debug("每行记录：{}", ss);
		}

		// 存放处理结果
		List<NodeMgr> list = new ArrayList<NodeMgr>();

		for (int i = 0; i < respStr.length; ++i) {
			NodeMgr node = new NodeMgr();
			List<HostMgr> hostList = new ArrayList<HostMgr>();
			String[] s = respStr[i].split(" ",3);
			logger.debug("查询结果的记录中的列数：{}", s.length);
			node.setNode(s[0]);
			node.setInvalid(s[1]);
			if(s.length>=3){
				String temp = s[2];
				temp = temp.replaceAll("\\(0\\)", "").replaceAll("\\(1\\)", "");
				node.setHosts(temp);
			}
			
			list.add(node);
		}
		return list;
	}


	@Override
	public void afterPropertiesSet() throws Exception {
		this.servletContext = dictDataServiceImpl.getServletContext();
	  	logger.info("初始化服务节点ip和port配置,servletContext:"+servletContext); 
	    Map<String,Map<String,String>> dictMap = (Map<String, Map<String, String>>) this.servletContext.getAttribute("dictMap");
	    
	    this.ibms_ip = 	  dictMap.get("http.ibms").get("ip");
	    this.ibms_port =  dictMap.get("http.ibms").get("port");
	    this.ibms_nodes = dictMap.get("http.ibms").get("query.nodes");
	    this.url = ("http://" + this.ibms_ip + ":" + this.ibms_port + "/");
	    this.query_nodes= dictMap.get("http.ibms").get("query.nodes");
	    this.add_node= dictMap.get("http.ibms").get("add.node");
	    this.delete_node= dictMap.get("http.ibms").get("delete.node");
	    this.update_node= dictMap.get("http.ibms").get("update.node");
	    this.add_host= dictMap.get("http.ibms").get("add.host");
	    this.delete_host= dictMap.get("http.ibms").get("delete.host");
		
	}

	// 删除node
	@Override
	public String deleteNode(NodeMgr nodeMgr) {
		
		String paramsJson = objToJson(nodeMgr);
		logger.debug("删除记录的主键json：{}", paramsJson);
		String response = this.fSHttpServiceImpl.sendPostRequest(this.url
				+ this.delete_node, paramsJson);
		if (!StringUtil.isEmpty(response)) {
			logger.debug("删除成功");
		}
		return response;

	}

	// 修改node 
	@Override
	public String updateNode(NodeMgr nodeMgr) {
		String paramsJson = objToJson(nodeMgr);
		logger.debug("修改记录json：{}", paramsJson);
		String response = this.fSHttpServiceImpl.sendPostRequest(this.url
				+ this.update_node, paramsJson);
		if (!StringUtil.isEmpty(response)) {
			logger.debug("修改成功");
		}
		return response;

	}

	// 增加node
	@Override
	public String addNode(NodeMgr nodeMgr) {
		String paramsJson = objToJson(nodeMgr);
		logger.debug("增加记录json：{}", paramsJson);
		String response = this.fSHttpServiceImpl.sendPostRequest(this.url
				+ this.add_node, paramsJson);
		if (!StringUtil.isEmpty(response)) {
			logger.debug("增加成功");
		}
		return response;
	}	

	public String objToJson(Object obj) {
		return JSON.toJSONString(obj);

	}

}
